package com.wang.data.client;

import org.springframework.stereotype.Component;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; 

@Component
public class WClient {
	private String host;
	private int port;

	public WClient() {
	}

	public void connect(int number) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class);
			bootstrap.option(ChannelOption.TCP_NODELAY, true);
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.handler(new NettyClientInitializer());

			Channel channel = bootstrap.connect("localhost", 9001).sync().channel();

			for (int i = 0; i < number; i++) {
				String message = "{\"name\":\"admin\",\"age\":" + i + "}\n";
				channel.writeAndFlush(message);
			}

			channel.closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		String host = "127.0.0.1";
		int port = 9001;
		WClient nettyClient = new WClient();
		nettyClient.connect(3);
		System.out.println("send  finished");
	}

	public void send(int number) {
		connect(number);
	}

}
